import config from './config.js';

// API基础配置
const api = {
  baseUrl: config.apiBaseUrl,
  
  // 获取请求头（添加认证信息）
  getHeaders() {
    const token = uni.getStorageSync('token');
    console.log('当前token:', token); // 添加调试信息
    return token ? { 'Authorization': `Bearer ${token}` } : {};
  },
  
  // 模拟数据开关 - 添加模拟数据支持
  useMockData: false, // 设置为false禁用模拟数据，使用真实后端API
  
  // 通用请求方法
  async request(url, options = {}) {
    console.log(`发起请求: ${options.method || 'GET'} ${this.baseUrl + url}`, options.data || ''); // 添加调试信息
    
    // 如果使用模拟数据，拦截请求并返回模拟数据
    if (this.useMockData) {
      console.log('正在使用模拟数据模式');
      const mockResponse = await this.getMockResponse(url, options);
      if (mockResponse) {
        console.log(`返回模拟数据: ${url}`, mockResponse);
        return mockResponse;
      }
    }
    
    const headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'X-Requested-With': 'XMLHttpRequest',
      ...this.getHeaders(),
      ...(options.headers || {})
    };
    
    return new Promise((resolve, reject) => {
      uni.request({
        url: this.baseUrl + url,
        method: options.method || 'GET',
        data: options.data,
        header: headers,
        withCredentials: true, // 添加跨域凭证支持
        success: (res) => {
          console.log(`请求成功: ${options.method || 'GET'} ${url}`, res.statusCode, res.data); // 添加调试信息
          
          // 检查是否是未授权错误(401)
          if (res.statusCode === 401) {
            console.error('未授权错误(401):', res.data); // 添加调试信息
            
            // 清除本地存储的用户信息
            uni.removeStorageSync('token');
            uni.removeStorageSync('userId');
            uni.removeStorageSync('username');
            
            // 提示用户重新登录
            uni.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none',
              complete: () => {
                // 重定向到登录页
                setTimeout(() => {
                  uni.reLaunch({
                    url: '/pages/login/login'
                  });
                }, 1500);
              }
            });
            reject(new Error('登录已过期'));
            return;
          }
          
          // 检查是否是跨域错误(403)
          if (res.statusCode === 403) {
            console.error('跨域错误(403):', res.data); // 添加调试信息
            resolve({
              code: 403,
              message: '服务器拒绝请求，可能是跨域问题',
              data: null
            });
            return;
          }
          
          // 检查后端返回的错误信息
          if (res.statusCode !== 200 || (res.data && res.data.code !== 200)) {
            console.error('API错误:', url, res.statusCode, res.data); // 添加调试信息
            resolve(res.data || {
              code: res.statusCode,
              message: res.errMsg || '未知错误',
              data: null
            }); // 仍然返回数据，让调用者处理错误
            return;
          }
          
          resolve(res.data);
        },
        fail: (err) => {
          console.error(`请求失败: ${options.method || 'GET'} ${url}`, err); // 添加调试信息
          
          // 网络连接问题 - 如果配置为使用模拟数据，则在网络失败时自动使用模拟数据
          if (this.useMockData) {
            console.log('网络请求失败，使用模拟数据');
            this.getMockResponse(url, options).then(mockResponse => {
              if (mockResponse) {
                console.log(`返回模拟数据: ${url}`, mockResponse);
                resolve(mockResponse);
              } else {
                // 没有对应的模拟数据
                this.showNetworkError(err);
                reject(err);
              }
            });
          } else {
            this.showNetworkError(err);
            reject(err);
          }
        }
      });
    });
  },
  
  // 显示网络错误提示
  showNetworkError(err) {
    // 网络连接问题
    if (err.errMsg && err.errMsg.includes('request:fail')) {
      uni.showToast({
        title: '网络连接失败，请检查网络或服务器状态',
        icon: 'none'
      });
    } else {
      // 其他网络错误提示
      uni.showToast({
        title: '网络请求失败: ' + (err.errMsg || '未知错误'),
        icon: 'none'
      });
    }
  },
  
  // 模拟响应数据 - 根据请求URL和方法返回对应的模拟数据
  async getMockResponse(url, options) {
    const method = options.method || 'GET';
    
    // 模拟登录
    if (url === '/auth/login' && method === 'POST') {
      const { username, password } = options.data;
      if (username === 'admin' && password === '123456') {
        // 模拟成功登录
        const mockToken = 'mock_token_' + Date.now();
        uni.setStorageSync('token', mockToken);
        uni.setStorageSync('userId', '1');
        uni.setStorageSync('username', username);
        
        return {
          code: 200,
          message: '登录成功',
          data: {
            token: mockToken,
            userId: '1',
            username: username
          }
        };
      } else {
        // 模拟登录失败
        return {
          code: 401,
          message: '用户名或密码错误',
          data: null
        };
      }
    }
    
    // 检查是否已登录（模拟认证）
    const token = uni.getStorageSync('token');
    if (!token && !url.includes('/auth/')) {
      return {
        code: 401,
        message: '未登录或登录已过期',
        data: null
      };
    }
    
    // 模拟用户信息
    if (url === '/users/me') {
      return {
        code: 200,
        message: '获取成功',
        data: {
          id: '1',
          username: uni.getStorageSync('username') || 'admin',
          email: 'admin@example.com',
          createdAt: '2023-01-01T00:00:00.000Z'
        }
      };
    }
    
    // 模拟获取日程列表
    if (url.startsWith('/events') && method === 'GET') {
      const mockEvents = this.getMockEvents();
      return {
        code: 200,
        message: '获取成功',
        data: mockEvents
      };
    }
    
    // 模拟获取任务列表
    if (url.startsWith('/tasks') && method === 'GET') {
      let mockTasks = this.getMockTasks();
      
      // 如果是按日期获取任务
      if (url.includes('/date/')) {
        const date = url.split('/date/')[1];
        mockTasks = mockTasks.filter(task => task.dueDate === date);
      }
      
      // 如果是按分类获取任务
      if (url.includes('?categoryId=')) {
        const categoryId = url.split('?categoryId=')[1];
        if (categoryId) {
          mockTasks = mockTasks.filter(task => task.categoryId === categoryId);
        }
      }
      
      return {
        code: 200,
        message: '获取成功',
        data: mockTasks
      };
    }
    
    // 模拟获取分类列表
    if (url === '/categories' && method === 'GET') {
      return {
        code: 200,
        message: '获取成功',
        data: this.getMockCategories()
      };
    }
    
    // 对于其他请求，简单返回成功
    if (method === 'POST' || method === 'PUT' || method === 'DELETE' || method === 'PATCH') {
      const mockId = Date.now().toString();
      const mockData = {
        id: mockId,
        ...options.data
      };
      
      return {
        code: 200,
        message: '操作成功',
        data: mockData
      };
    }
    
    // 未匹配的请求返回null，将会继续尝试发起实际网络请求
    return null;
  },
  
  // 获取模拟日程数据
  getMockEvents() {
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    
    return [
      {
        id: '1',
        title: '项目会议',
        date: formatDate(today),
        startTime: '09:00',
        endTime: '10:30',
        description: '讨论项目进度和下一步计划'
      },
      {
        id: '2',
        title: '午餐约会',
        date: formatDate(today),
        startTime: '12:00',
        endTime: '13:30',
        description: '与客户共进午餐'
      },
      {
        id: '3',
        title: '团队建设活动',
        date: formatDate(tomorrow),
        startTime: '14:00',
        endTime: '17:00',
        description: '团队外出活动'
      }
    ];
  },
  
  // 获取模拟任务数据
  getMockTasks() {
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
    
    return [
      {
        id: '1',
        title: '完成项目文档',
        description: '编写项目设计文档和用户手册',
        dueDate: formatDate(today),
        dueTime: '18:30',
        priority: 2,
        categoryId: 'work',
        completed: false
      },
      {
        id: '2',
        title: '购买生日礼物',
        description: '为朋友购买生日礼物',
        dueDate: formatDate(tomorrow),
        dueTime: '15:00',
        priority: 1,
        categoryId: 'personal',
        completed: false
      },
      {
        id: '3',
        title: '健身锻炼',
        description: '每天跑步30分钟',
        dueDate: formatDate(today),
        dueTime: '23:59',
        priority: 0,
        categoryId: 'personal',
        completed: true
      }
    ];
  },
  
  // 获取模拟分类数据
  getMockCategories() {
    return [
      {
        id: 'work',
        name: '工作'
      },
      {
        id: 'personal',
        name: '个人'
      }
    ];
  },
  
  // 登录
  login(username, password) {
    console.log('登录请求:', username); // 添加调试信息，不记录密码
    return this.request('/auth/login', {
      method: 'POST',
      data: { username, password }
    });
  },
  
  // 注册
  register(username, password) {
    console.log('注册请求:', username); // 添加调试信息，不记录密码
    return this.request('/auth/register', {
      method: 'POST',
      data: { username, password }
    });
  },
  
  // 退出登录
  logout() {
    return this.request('/auth/logout', {
      method: 'POST'
    });
  },
  
  // 获取用户信息
  getUserInfo() {
    return this.request('/users/me');
  },
  
  // 日程相关API
  getEvents(startDate, endDate) {
    return this.request(`/events?startDate=${startDate}&endDate=${endDate}`);
  },
  
  createEvent(event) {
    return this.request('/events', {
      method: 'POST',
      data: event
    });
  },
  
  updateEvent(id, event) {
    return this.request(`/events/${id}`, {
      method: 'PUT',
      data: event
    });
  },
  
  deleteEvent(id) {
    return this.request(`/events/${id}`, {
      method: 'DELETE'
    });
  },
  
  // 任务相关API
  getTasks(categoryId = '') {
    const url = categoryId ? `/tasks?categoryId=${categoryId}` : '/tasks';
    return this.request(url);
  },
  
  getTasksByDate(date) {
    return this.request(`/tasks/date/${date}`);
  },
  
  createTask(task) {
    return this.request('/tasks', {
      method: 'POST',
      data: task
    });
  },
  
  updateTask(id, task) {
    return this.request(`/tasks/${id}`, {
      method: 'PUT',
      data: task
    });
  },
  
  deleteTask(id) {
    return this.request(`/tasks/${id}`, {
      method: 'DELETE'
    });
  },
  
  toggleTask(id) {
    return this.request(`/tasks/${id}/toggle`, {
      method: 'PATCH'
    });
  },
  
  // 分类相关API
  getCategories() {
    return this.request('/categories');
  },
  
  createCategory(category) {
    return this.request('/categories', {
      method: 'POST',
      data: category
    });
  },
  
  updateCategory(id, category) {
    return this.request(`/categories/${id}`, {
      method: 'PUT',
      data: category
    });
  },
  
  deleteCategory(id) {
    return this.request(`/categories/${id}`, {
      method: 'DELETE'
    });
  }
};

export default api; 